import { spotMarketBatch, spotMarketCommon } from "@src/api/spotMarket"

import type { GetAllNodeDataParams, NodeMsg, OneNodeOriginData } from "./type"
import { getSpotMartetReqInfo } from "../../generate"
import { validateJSON } from "@src/utils/common"

import { DataSourceTypeEnum } from "@src/globalData/enum";

  /**
   * 【现货市场】-【现货交易】-【日前交易结果】-【一次日前节点电价查询】
   * 全网所有节点日前出清节点电价
   * D + 1
   * AHEAD_NODE_PRICE_INFO = "ahead_node_price_info"
   */
  /**
   * https://pmos.sd.sgcc.com.cn:18080/trade/main/home/changeDate.do?pdate=2024-03-19&_=1711692352927
   * 【现货市场】-【现货交易】-【实时交易结果】-【实时节点电价查询】
   * 全网所有节点实时出清节点电价-正式
   * D - 1
   * ACT_NODE_PRICE_INFO = "act_node_price_info",
   */
export const defaultNodeData:NodeMsg = {cityName:'枣庄', nodeName:'丰泽站', nodeId: 'nodeid_115404740451370230'}
// {cityName:'日照', nodeName:'石井站', nodeId: 'nodeid_115404740451370654'}
// {cityName:'日照', nodeName:'石井站', nodeId: 'nodeid_115404740451370655'}


export const dataTypeList:{value:DataSourceTypeEnum, label:string}[] = [
  {
    value: DataSourceTypeEnum.AHEAD_NODE_PRICE_INFO,
    label: '日前出清节点电价 D+1'
  },
  {
    value: DataSourceTypeEnum.ACT_NODE_PRICE_INFO,
    label: '实时出清节点电价-正式 d-1'
  }
]

type GetOneNodeDataParams = {
  headers: HeadersInit,
  reqType:DataSourceTypeEnum, 
  nodeMsg:NodeMsg,
  pdate: string
}
type YunNaoSaveData = {
  runDate: string,
  nodeId: string,
  cityName: string,
  nodeName: string,
  nodePrice: string | number
}[]

/**
 * 获取一个节点的数据
 * @param params GetOneNodeDataParams
 * @returns
 */
const getOneNodeData = async (params:GetOneNodeDataParams):Promise<OneNodeOriginData> => {
  const {reqType, nodeMsg:{nodeId}, headers} = params
  const data:OneNodeOriginData = await spotMarketBatch?.[reqType]?.({headers, unitid:nodeId, pdate:'' })
  return Promise.resolve(data)
}

/**
 * 获取120个节点的数据
 * @param ruleForm RuleForm
 * @param headersInfo HeadersInit
 * @returns 
 */
export const getAllNodeData = async (ruleForm:GetAllNodeDataParams, headersInfo:HeadersInit | undefined = undefined, node:NodeMsg = defaultNodeData) => {
  try {
    let reqInfo = {headers:headersInfo}
    if(!headersInfo) reqInfo = await getSpotMartetReqInfo(true) as { headers: HeadersInit; }
    if(!reqInfo?.headers) return Promise.reject(new Error('getAllNodeData  headers'))
    const headers = reqInfo.headers
  
    const {certainDate} = ruleForm

    // 设置数据日期
    await spotMarketCommon?.sdSpotMarketChangeDate?.(certainDate)

    const reqParams:GetOneNodeDataParams = {headers,reqType: DataSourceTypeEnum.AHEAD_NODE_PRICE_INFO,nodeMsg: node, pdate: certainDate}
    // 日前
    const aheadData:OneNodeOriginData = await getOneNodeData({...reqParams,reqType: DataSourceTypeEnum.AHEAD_NODE_PRICE_INFO})
    // 实时
    const actData:OneNodeOriginData = await getOneNodeData({ ...reqParams, reqType:DataSourceTypeEnum.ACT_NODE_PRICE_INFO })
    
    return Promise.resolve({aheadData, actData, certainDate})
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

  // 校验是否可解析为 json
  export const validateNodes = (rule: any, value: any, callback: any) => {
    if (!validateJSON(value)) {
      callback(new Error('输入有误'))
    } else {
      callback()
    }
  }

  export const validateUniqueCode = (rule: any, value: any, callback: any) => {
    if (String(value).toLowerCase() !== 'hd2024') {
      callback(new Error('验证码输入错误'))
    } else {
      callback()
    }
  }

  export const dealValue = (val:any) => {
    if(val === undefined || val === null) return ''
    return /^([\d|\-|])?[\d|\.]+$/.test(val) ? val : ''
  }

  export const getMinMaxDifferenc = (list:string[]) => {
    const numList:number[] = []

    list.forEach(val => /^([\d|\-|])?[\d|\.]+$/.test(val) && numList.push(Number(val)))
    numList.sort((a,b) => a - b)

    let [max, min, difference]:(string | number)[] = ['', '', '']

    if(numList.length === 1) {
      [max, min, difference] = [numList[0], numList[0], 0]
    }

    if(numList.length > 1) {
      [max, min] = [Math.max(...numList), Math.min(...numList)]
      difference = max - min
    }

    return [max, min, difference]
  }